<?php

namespace app\modules\backend\controllers;

use Yii;
use app\tools\Re;
use app\models\Customer;
use app\models\CustomerCollect;
use app\models\CustomerAppointment;

class CustomerController extends BaseController
{
  public $state_name_arr = ['待服务','服务中','服务成功'];

  public function actionList(){
    $nickname = Yii::$app->request->post('nickname', '');
    $name = Yii::$app->request->post('name', '');
    $phone = Yii::$app->request->post('phone', '');
    $page = Yii::$app->request->post('page', 0);
    $page_size = Yii::$app->request->post('page_size', 20);
    $query = Customer::find()->where(['status' => [0,1]]);
    if (!empty($nickname)) {
      $query->andWhere(['like', 'nickname', $nickname]);
    }
    if (!empty($name)) {
      $query->andWhere(['like', 'name', $name]);
    }
    if (!empty($phone)) {
      $query->andWhere(['like', 'phone', $phone]);
    }
    $list = $query->orderBy(' created_at desc')->limit($page_size)->offset($page_size*$page)->all();
    $data = [];
    if ($list) {
      foreach($list as $v) {
        $data[] = [
          'id' => $v->id,
          'nickname' => $v->nickname,
          'name' => $v->name,
          'phone' => $v->phone,
          'icon' => $v->icon,
          'openid' => $v->openid,
          'created_time' => date('Y-m-d H:i:s', $v->created_at)
        ];
      }
    }
    return Re::data([
      'data' => $data,
      'totalPage' => $query->count(),
      'currentPage' => $page,
      'perPage' => $page_size
    ]);
  }

  public function actionCollectList(){
    $customer_id = Yii::$app->request->post('customer_id', 0);
    $good_id = Yii::$app->request->post('good_id', 0);
    $page = Yii::$app->request->post('page', 0);
    $page_size = Yii::$app->request->post('page_size', 20);
    $query = CustomerCollect::find()->where(['is_collect' => 1]);
    if (!empty($customer_id)) {
      $query->andWhere(['customer_id' => $customer_id]);
    }
    if (!empty($good_id)) {
      $query->andWhere(['good_id' => $good_id]);
    }
    $list = $query->orderBy('created_at desc')->limit($page_size)->offset($page_size*$page)->all();
    $data = [];
    if ($list) {
      foreach($list as $v) {
        $data[] = [
          'id' => $v->id,
          'customer_id' => $v->customer_id,
          'customer_name' => $v->customer->name,
          'good_id' => $v->good_id,
          'good_name' => $v->good_id ? $v->good->name : '',
          'created_time' => date('Y-m-d H:i:s', $v->created_at)
        ];
      }
    }
    return Re::data([
      'data' => $data,
      'totalPage' => $query->count(),
      'currentPage' => $page,
      'perPage' => $page_size
    ]);
  }

  public function actionListForSelect(){
    $data = Customer::find()->where(['status' => 1])->select("id, name")->all();
    return Re::data(['data' => $data,]);
  }
}
